package cn.itsource.ymcc.mq;

import cn.itsource.ymcc.constants.BaseConstants;
import cn.itsource.ymcc.domain.CourseUserLearn;
import cn.itsource.ymcc.domain.PayFlow;
import cn.itsource.ymcc.dto.AlipayNotifyDto;
import cn.itsource.ymcc.service.ICourseUserLearnService;
import cn.itsource.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Slf4j
@Component
@RocketMQMessageListener(topic = BaseConstants.PayMQ.TOPIC_PAY_RESULT,
        selectorExpression=BaseConstants.PayMQ.TAGS_BUYCOURSE_RESULT_2COURSE
        ,consumerGroup = "service-course-pay-reslut-consumer"
        ,messageModel = MessageModel.CLUSTERING )
public class BuyCoursePayResultMessageConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private ICourseUserLearnService courseUserLearnService;

    //课程订单支付结果处理
    @Override
    @Transactional
    public void onMessage(MessageExt message) {
        String msg = new String(message.getBody(), CharsetUtil.UTF_8);
        log.info("课程消费者,处理支付结果收到消息-> {} ",msg);
        AlipayNotifyDto alipayNotifyDto = JSON.parseObject(msg, AlipayNotifyDto.class);
        //幂等处理
        synchronized (this){
            CourseUserLearn courseUserLearn = courseUserLearnService.selectByCourseOrderNo(alipayNotifyDto.getOut_trade_no());
            //已经保存了用户和课程关系
            if(courseUserLearn != null)return;
        }

        //拿到用户和课程ID：方法有问题
        Map<String, Object> passbackParams = alipayNotifyDto.passbackParams2Map();
        AssertUtil.isNotNull(passbackParams,"回执参数获取失败，无效的UserId和CourseId");
        Long userId = Long.valueOf(passbackParams.get("userId").toString());
        String relationId = passbackParams.get("relationId").toString();
        log.info("保存用户和课程关系 -> {}-{} ",userId,relationId);

        if(relationId.indexOf(",") > 0){
            String[] relationIdStrs = relationId.split(",");
            for (String relationIdStr : relationIdStrs) {
                Long courseId = Long.valueOf(relationIdStr);
                courseUserLearnService.create(userId,courseId,alipayNotifyDto.getOut_trade_no());
            }
        }else{
            Long courseId = Long.valueOf(passbackParams.get("relationId").toString());
            //保存用户和课程的关系
            courseUserLearnService.create(userId,courseId,alipayNotifyDto.getOut_trade_no());
        }
    }
}
